// src/modules/project/hooks.ts
"use client";

import useSWR, { SWRConfiguration, mutate } from "swr";
import useSWRMutation from "swr/mutation";
import { projectApi } from "./api";
import type {
  Project,
  ProjectCreate,
  ProjectUpdate,
  ProjectQuery,
  ProjectListResponse,
} from "./types";

/* -------------------- SWR Keys -------------------- */
const LIST_KEY = "/project:list";
const detailKey = (id: string) => `/project/${id}:detail`;

/* -------------------- 列表 key 生成 -------------------- */
function makeProjectsKey(q?: ProjectQuery): string {
  const usp = new URLSearchParams();
  if (q?.page) usp.set("page", String(q.page));
  if (q?.page_size) usp.set("page_size", String(q.page_size));
  if (q?.project_number) usp.set("project_number", q.project_number);
  if (q?.project_type) usp.set("project_type", q.project_type);
  if (q?.status) usp.set("status", q.status);
  
  const qs = usp.toString();
  return `${LIST_KEY}${qs ? `?${qs}` : ""}`;
}

/* -------------------- 读取 -------------------- */
export function useProjects(
  q?: ProjectQuery,
  config?: SWRConfiguration<ProjectListResponse>
) {
  const key = makeProjectsKey(q);
  const fetcher = () => projectApi.listProjects(q);
  return useSWR<ProjectListResponse>(key, fetcher, {
    revalidateOnFocus: false,
    ...(config ?? {}),
  });
}

export function useProject(
  id: string,
  config?: SWRConfiguration<Project>
) {
  const key = detailKey(id);
  const fetcher = () => projectApi.getProject(id);
  return useSWR<Project>(key, fetcher, {
    revalidateOnFocus: false,
    ...(config ?? {}),
  });
}

/* -------------------- 写入 -------------------- */
export function useCreateProject() {
  const { trigger, isMutating, data, error } = useSWRMutation(
    ["/project", "create"],
    async (_key: unknown, { arg }: { arg: ProjectCreate }) => {
      const created = await projectApi.createProject(arg);
      // 刷新列表数据
      await mutateProjects();
      return created;
    }
  );
  return {
    createProject: (payload: ProjectCreate) => trigger(payload),
    creating: isMutating,
    data: data as Project | undefined,
    error,
  };
}

export function useUpdateProject() {
  const { trigger, isMutating, data, error } = useSWRMutation(
    ["/project", "update"],
    async (_key: unknown, { arg }: { arg: ProjectUpdate }) => {
      const updated = await projectApi.updateProject(arg);
      // 刷新相关数据
      await Promise.allSettled([mutateProject(arg.id), mutateProjects()]);
      return updated;
    }
  );
  return {
    updateProject: (payload: ProjectUpdate) => trigger(payload),
    updating: isMutating,
    data: data as boolean | undefined,
    error,
  };
}

export function useDeleteProject() {
  const { trigger, isMutating, data, error } = useSWRMutation(
    ["/project", "delete"],
    async (_key: unknown, { arg }: { arg: string }) => {
      const result = await projectApi.deleteProject(arg);
      // 刷新列表数据
      await mutateProjects();
      return result;
    }
  );
  return {
    deleteProject: (id: string) => trigger(id),
    deleting: isMutating,
    data: data as boolean | undefined,
    error,
  };
}

/* -------------------- 手动刷新 -------------------- */
export function mutateProjects() {
  return mutate((key: unknown) => typeof key === "string" && key.startsWith(LIST_KEY));
}

export function mutateProject(id: string) {
  return mutate(detailKey(id));
}
